<template>
  <div class="trade-history">
    <h2>交易历史</h2>
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else>
      <div class="filters">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input 
              v-model="filters.symbol" 
              placeholder="筛选股票代码"
              @input="filterTrades"
              clearable
            />
          </el-col>
          <el-col :span="8">
            <el-select v-model="filters.type" @change="filterTrades" placeholder="请选择交易类型" clearable style="width: 100%;">
              <el-option label="全部" value=""></el-option>
              <el-option label="买入" value="BUY"></el-option>
              <el-option label="卖出" value="SELL"></el-option>
            </el-select>
          </el-col>
        </el-row>
      </div>
      
      <el-table :data="filteredTrades" height="500" style="width: 100%" v-if="filteredTrades.length > 0">
        <el-table-column prop="id" label="交易ID" min-width="100"></el-table-column>
        <el-table-column prop="symbol" label="股票代码" min-width="100"></el-table-column>
        <el-table-column label="交易类型" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.type === 'BUY' ? 'success' : 'danger'">
              {{ scope.row.type === 'BUY' ? '买入' : '卖出' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" min-width="100" align="right"></el-table-column>
        <el-table-column label="价格" min-width="120" align="right">
          <template #default="scope">
            ¥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="总金额" min-width="120" align="right">
          <template #default="scope">
            ¥{{ (scope.row.quantity * scope.row.price).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="100"></el-table-column>
        <el-table-column label="交易时间" min-width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.timestamp) }}
          </template>
        </el-table-column>
      </el-table>
      <div v-else class="no-trades">
        <p>暂无交易记录</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import apiService from '../services/ApiService';

const trades = ref([]);
const filteredTrades = ref([]);
const loading = ref(false);
const error = ref(null);
const filters = ref({
  symbol: '',
  type: ''
});

onMounted(async () => {
  await fetchTradeHistory();
});

const fetchTradeHistory = async () => {
  try {
    loading.value = true;
    error.value = null;
    
    const response = await apiService.getAllTrades();
    // 修复：检查响应中是否有error属性来判断是否出错
    if (!response || response.error) {
      error.value = response?.error || '获取交易历史失败';
    } else {
      trades.value = response.data;
      filteredTrades.value = [...trades.value];
    }
  } catch (err) {
    error.value = '网络错误，请稍后重试';
    console.error('获取交易历史失败:', err);
  } finally {
    loading.value = false;
  }
};

const filterTrades = () => {
  filteredTrades.value = trades.value.filter(trade => {
    const symbolMatch = filters.value.symbol 
      ? trade.symbol.toLowerCase().includes(filters.value.symbol.toLowerCase()) 
      : true;
    const typeMatch = filters.value.type 
      ? trade.type === filters.value.type 
      : true;
    
    return symbolMatch && typeMatch;
  });
};

const formatDateTime = (timestamp) => {
  if (!timestamp) return '-';
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN');
};
</script>

<style scoped>
.trade-history {
  padding: 20px;
}

.loading, .error {
  text-align: center;
  padding: 20px;
}

.error {
  color: red;
}

.filters {
  margin-bottom: 20px;
}

.no-trades {
  text-align: center;
  padding: 30px;
  color: #666;
}
</style>